'use strict';

angular.module('afasApp')
.config(function($provide) {
  $provide.decorator('uiSrefDirective',
    ['$delegate', '$log', 'principal', function ($delegate, $log, principal) {
          var directive = $delegate[0];

          directive.compile = function() {
            return function(scope, element, attrs) {
              var stateName = attrs.uiSref.replace(/\(.+\)$/g, ''); // strip out the state params
              var injector = element.injector();
              var state = injector && injector.get('$state').get(stateName);

              // Watch for null (abstract) states and warn about them rather than erroring.
              if (!state) {
                $log.warn('Could not find state:', attrs.uiSref);

              } else if (state.data.roles) {

                // If the user lacks sufficient permissions, hide this state from them.
                if (!principal.isInAnyRole(state.data.roles)) {
                  element.remove();
                }
              }

              // Otherwise pass through and let uiSref handle the rest
              directive.link.apply(this, arguments);
            };
          };

          return $delegate;
        }]);
});